package me.sdevil507.supports.upload;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import me.sdevil507.supports.upload.helper.FileDetectionHelper;
import me.sdevil507.supports.upload.service.AbstractUploadFileHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.util.UUID;

/**
 * 七牛云存储上传
 *
 * @author sdevil507
 */
@Slf4j
@Component
public class QiNiuUploadFileHandler extends AbstractUploadFileHandler {

    private final QiNiuUploadProperties qiNiuUploadProperties;

    public QiNiuUploadFileHandler(FileDetectionHelper fileDetectionHelper, QiNiuUploadProperties qiNiuUploadProperties) {
        super(fileDetectionHelper);
        this.qiNiuUploadProperties = qiNiuUploadProperties;
    }

    @Override
    protected String save(File tempFile, String originalFileName) {
        try {
            //密钥配置
            Auth auth = Auth.create(qiNiuUploadProperties.getAccessKey(), qiNiuUploadProperties.getSecertKey());
            //自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
            Configuration c = new Configuration(Region.autoRegion());
            //创建上传对象
            UploadManager uploadManager = new UploadManager(c);
            //简单上传，使用默认策略，只需要设置上传的空间名就可以了
            String token = auth.uploadToken(qiNiuUploadProperties.getBucket());
            //构建上传文件,并上传
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String fileName = UUID.randomUUID() + extension;
            Response response = uploadManager.put(FileCopyUtils.copyToByteArray(tempFile), fileName, token);
            //上传反馈
            if (response.isOK()) {
                return fileName;
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("七牛云上传失败:", e);
            return null;
        }
    }
}
